#!/bin/bash
# 安装MySQL及配置服务

# 引入公共配置
source ./common.sh

# 确保应用目录存在
app_home

function install_mysql() {
    # 创建mysql用户
    if ! id -u mysql >/dev/null 2>&1; then
        groupadd mysql
        useradd -r -g mysql -s /sbin/nologin mysql
    fi
    
    if [ `ls ${APPS_HOME} | grep ${Version} | tr -d "[0-9]"|tr -d "."|uniq|wc -l` -eq 5 ];then
        echo "文件已存在，切换版本中"
        rpm -e `rpm -qa |grep mysql` --nodeps 2>/dev/null
        cd ${Basedir}/download && ls |grep ${Version}|xargs yum -y localinstall
    else
        local list=( "common-" "libs-" "libs-compat-" "client-" "server-" )
        local el="-1.el7.x86_64.rpm"
        local v=`echo ${Version}|awk -F '.' '{print $1"."$2}'`
        
        for i in "${list[@]}";do
            echo "正在下载MySQL ${i}组件..."
            wget -P ${APPS_HOME} "${MYSQL_NAME}""$v""${MYSQL_NAME_END}"${i}"${Version}"${el}
            if [ $? -ne 0 ]; then
                error_exit "MySQL ${i}组件下载失败"
            fi
            yum -y localinstall ${APPS_HOME}/mysql-community-${i}"${Version}".*
        done
    fi
    
    systemctl start mysqld
}

function configure_mysql_service() {
    if [[ ! -f "${MYSQL_SERVICE}" ]];then
        echo "创建mysql服务文件"
        cat > ${MYSQL_SERVICE} <<EOF
[Unit]
Description=MySQL Server
Documentation=man:mysqld(8)
Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html
After=network.target
After=syslog.target

[Install]
WantedBy=multi-user.target

[Service]
User=mysql
Group=mysql

Type=forking

PIDFile=/var/run/mysqld/mysqld.pid

TimeoutSec=0

PermissionsStartOnly=true

ExecStartPre=/usr/bin/mysqld_pre_systemd

ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid \$MYSQLD_OPTS

EnvironmentFile=-/etc/sysconfig/mysql

LimitNOFILE = 5000

Restart=on-failure

RestartPreventExitStatus=1

PrivateTmp=false
EOF

        systemctl daemon-reload
        systemctl enable mysqld
        success_msg "MySQL服务配置完成"
        
        # 显示初始密码
        echo "MySQL初始密码："
        grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}'
        echo "请使用初始密码登录后修改：mysql_secure_installation"
    else
        echo "mysql服务文件已存在"
    fi
}

echo "开始安装MySQL..."

# 检查是否已安装mysql或mariadb
if (( $(rpm -qa | grep -i mysql | wc -l) > 0 || $(rpm -qa | grep -i mariadb | wc -l) > 0 )); then
    echo "系统中已安装mysql或mariadb"
    read -p "是否卸载自带mysql数据库(y/n): " check_mysql
    if [ "${check_mysql}" != "y" ];then
        echo "保留系统已有mysql数据库，退出安装"
        exit 0
    fi
    
    # 卸载已安装的版本
    rpm -qa|grep mysql|xargs rpm -e --nodeps 2>/dev/null
    rpm -qa|grep mariadb|xargs rpm -e --nodeps 2>/dev/null
fi

read -p "输入需要的mysql版本 (默认5.7.38): " Version
if [ -z "${Version}" ];then
    Version="5.7.38"
    echo "使用默认版本: $Version"
fi

# 安装依赖
yum -y install libaio

install_mysql
configure_mysql_service

success_msg "MySQL ${Version} 安装完成"
